/**
 * Copyright (c) 2021 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */
package io.renren.modules.stat.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.constant.Constant;
import io.renren.common.exception.RenException;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.stat.dao.StatChannelDao;
import io.renren.modules.stat.dao.StatDataDao;
import io.renren.modules.stat.dto.StatChannelDTO;
import io.renren.modules.stat.entity.StatChannelEntity;
import io.renren.modules.stat.service.StatChannelConfService;
import io.renren.modules.stat.service.StatChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 栏目管理
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service
public class StatChannelServiceImpl extends CrudServiceImpl<StatChannelDao, StatChannelEntity, StatChannelDTO> implements StatChannelService {

    @Autowired
    private StatDataDao statDataDao;
    @Autowired
    private StatChannelConfService statChannelConfService;

    @Override
    public QueryWrapper<StatChannelEntity> getWrapper(Map<String, Object> params) {
        QueryWrapper<StatChannelEntity> wrapper = new QueryWrapper<>();

        String channelCode = (String) params.get("channelCode");
        wrapper.like(StringUtils.isNotBlank(channelCode), "channel_code", channelCode);

        String channelName = (String) params.get("channelName");
        wrapper.like(StringUtils.isNotBlank(channelName), "channel_name", channelName);

        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)) {
            wrapper.eq("status", Integer.parseInt(status));
        }

        wrapper.orderByAsc("sort");

        return wrapper;
    }

    @Override
    public List<StatChannelDTO> list(Map<String, Object> params) {
        List<StatChannelEntity> entityList = baseDao.selectList(getWrapper(params));

        return ConvertUtils.sourceToTarget(entityList, StatChannelDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long[] ids) {
        for (Long id : ids) {
            statChannelConfService.deleteByChannel(id);
        }
        baseDao.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dataImport(Long id, MultipartFile file) {
        StatChannelDTO dto = get(id);
        if (dto != null) {
            try {
                ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
                List<List<Object>> readAll = reader.read();
                List<Object> titleRow = readAll.get(0);
                String tableName = "stat_" + dto.getChannelCode();
                statDataDao.dropTable(tableName);
                statDataDao.createTable(tableName, titleRow);
                for (int i = 1; i < readAll.size(); i++) {
                    List<Object> row = readAll.get(i);
                    List<String> dataList = new ArrayList<>(titleRow.size());
                    for (int j = 0; j < titleRow.size(); j++) {
                        if (row.size() > j) {
                            if (row.get(j) == null) {
                                dataList.add("");
                            } else {
                                dataList.add(String.valueOf(row.get(j)));
                            }
                        } else {
                            dataList.add("");
                        }
                    }
                    dataList.add(0, String.valueOf(i));
                    statDataDao.insertTable(tableName, titleRow, dataList);
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new RenException("导入失败");
            }
        }
    }

    @Override
    public List<String> columns(Map<String, Object> params) {
        if (params.get("channelId") == null) {
            throw new RenException("参数错误，channelId为空");
        }
        Long channelId = Long.valueOf((String) params.get("channelId"));
        StatChannelDTO dto = get(channelId);
        String tableName = "stat_" + dto.getChannelCode();
        params.put("tableName", tableName);
        return statDataDao.getColumns(params);
    }

    @Override
    public PageData<Map<String, String>> dataPage(Map<String, Object> params) {
        if (params.get("channelId") == null) {
            throw new RenException("参数错误，channelId为空");
        }
        Long channelId = Long.valueOf((String) params.get("channelId"));
        StatChannelDTO dto = get(channelId);
        String tableName = "stat_" + dto.getChannelCode();
        params.put("tableName", tableName);
        //分页参数
        long curPage = 1;
        long limit = 10;

        if (params.get(Constant.PAGE) != null) {
            curPage = Long.parseLong((String) params.get(Constant.PAGE));
            params.put(Constant.PAGE, (curPage - 1) * limit);
        }
        if (params.get(Constant.LIMIT) != null) {
            limit = Long.parseLong((String) params.get(Constant.LIMIT));
            params.put(Constant.LIMIT, limit);
        }
        List<Map<String, String>> list = statDataDao.getList(params);
        long count = statDataDao.pageCount(params);
        return new PageData<>(list, count);
    }
}